//------------------------------------------------------------------------------
//	file midi_decoder.c
//	brief
//		Decode MIDI messages. This includes:
//		- MIDI channel voice messages
//		- MIDI system common messages
//		- MIDI system real-time messages
//		- MIDI time code
//		- MIDI machine control
//
//	$Id: midi_decoder.c 3 2014-04-19 07:10:51Z ac.verbeck@gmail.com $
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
//	Copyright and Disclaimer Notice
//
//	The MIT License (MIT)
//	
//	Copyright (c) 2014 A.C. Verbeck
//	
//	Permission is hereby granted, free of charge, to any person obtaining a copy
//	of this software and associated documentation files (the "Software"), to deal
//	in the Software without restriction, including without limitation the rights
//	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//	copies of the Software, and to permit persons to whom the Software is
//	furnished to do so, subject to the following conditions:
//	
//	The above copyright notice and this permission notice shall be included in
//	all copies or substantial portions of the Software.
//	
//	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//	THE SOFTWARE.
//
//------------------------------------------------------------------------------

#include <stdio.h>
#include <conio.h>
#include <stdlib.h>

#include <stdint.h>																//	Standard int types
#include <stdbool.h>															//	Bool

#include <popt.h>
#include <windows.h>
#include <mmsystem.h>

#include "bi.h"
#include "debug.h"

#include "mm_err.h"
#include "cc_string.h"
#include "midi_const.h"

//----------------------------------------------------------------------------
// Local defines (options)
//----------------------------------------------------------------------------
#define OPT_PORT			0x0001
#define OPT_ABOUT			0x0100
#define OPT_VERBOSE			0x0200

//----------------------------------------------------------------------------
// Local data
//----------------------------------------------------------------------------
static poptContext		optCon;

//----------------------------------------------------------------------------
// Local functions
//----------------------------------------------------------------------------
static void CALLBACK MidiInProc(HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2);
static void Decode_MidiMsg(DWORD msg);
static void about(void);

//------------------------------------------------------------------------------
//	Main application
//	- read parameters
//	- start the midi port
//	- wait for characters
//------------------------------------------------------------------------------
int main(int argc, char* argv[])
{
	HMIDIIN		hMidiDevice = NULL;

	DWORD		nMidiPort = 0;
	MMRESULT	rVal;

	uint32_t	opt=0;
	int			idx=0;
	int			in_char=0;
	bool		tr_run = true;

	struct poptOption optionsTable[] = {
		{ "port",	'p', POPT_ARG_INT,	  &nMidiPort,	 'p', "MIDI port to use",					NULL	},
		{ "about",	'a', POPT_ARG_NONE,	  NULL,			 'a', "display information about the app",	NULL	},
		{ "verbose",'v', POPT_ARG_NONE,	  NULL,			 'v', "enable verbose mode",				NULL	},
		POPT_AUTOHELP
		POPT_TABLEEND
	};

//------------------------------------------------------------------------------
//	Process arguments
//------------------------------------------------------------------------------
	optCon = poptGetContext(NULL, argc, (const char **)argv, optionsTable, 0);
	poptSetOtherOptionHelp(optCon, "[OPTIONS]*");
	if (argc == 1) {
		about();
	}
	while ((idx = poptGetNextOpt(optCon)) >= 0) {
		switch (idx) {
		case 'p':
			opt |= OPT_PORT;
			break;
		case 'a':
			opt |= OPT_ABOUT;
			break;
		case 'v':
			opt |= OPT_VERBOSE;
			break;
		}
	}
	if (idx < -1) {
		fprintf(stderr, "%s: %s\n",
		        poptBadOption(optCon, POPT_BADOPTION_NOALIAS),
		        poptStrerror(idx));
		exit(opt);
	}
	if (opt & OPT_ABOUT) {
		bldinfoPrintBldInfo();
		exit(0);
	}
	TRACE_init((opt & OPT_VERBOSE) ? true : false);

//------------------------------------------------------------------------------
//	Check for MIDI ports
//------------------------------------------------------------------------------
	if (midiInGetNumDevs() == 0) {
		TRACE(INFO,"No Input MIDI devices\n")
		exit(1);
	}

//------------------------------------------------------------------------------
//	Open MIDI port
//------------------------------------------------------------------------------
	TRACE(INFO,"Opening MIDI port: %d",nMidiPort);
	rVal = midiInOpen(&hMidiDevice, nMidiPort, (DWORD)(void*)MidiInProc, 0, CALLBACK_FUNCTION);
	if (rVal != MMSYSERR_NOERROR) {
		TRACE(INFO,"midiInOpen() failed. Error code %d (%s)",rVal, getMMErrString(rVal));
		exit(1);
	}

//------------------------------------------------------------------------------
//	Wait for q or ESC key
//------------------------------------------------------------------------------
	midiInStart(hMidiDevice);
	while (tr_run == true) {
		in_char = _getch();
		switch (in_char) {
		case 'q':
			tr_run = false;
			break;
		case VK_ESCAPE:
			tr_run = false;
			break;
		}
	}

	return 0;
}

//----------------------------------------------------------------------------
// MIDI input driver callback
//----------------------------------------------------------------------------
static void CALLBACK MidiInProc(HMIDIIN hMidiIn, UINT wMsg, DWORD dwInstance, DWORD dwParam1, DWORD dwParam2)
{
	switch(wMsg) {
	case MIM_OPEN:
		TRACE(INFO, "MIM_OPEN");
		break;
	case MIM_CLOSE:
		TRACE(INFO, "MIM_CLOSE");
		break;
	case MIM_DATA:
		TRACE(INFO, "MIM_DATA: MIDI msg:%08x timestamp:%d", dwParam1, dwParam2);
		Decode_MidiMsg(dwParam1);
		break;
	case MIM_LONGDATA:
		TRACE(INFO, "MIM_LONGDATA: MIDI hdr:%08x timestamp:%d", dwParam1, dwParam2);
		break;
	case MIM_ERROR:
		TRACE(INFO, "MIM_ERROR");
		break;
	case MIM_LONGERROR:
		TRACE(INFO, "MIM_LONGERROR");
		break;
	case MIM_MOREDATA:
		TRACE(INFO, "MIM_MOREDATA");
		break;
	default:
		TRACE(INFO, "unknown wMsg");
		break;
	}
	return;
}

//----------------------------------------------------------------------------
// Decode MIDI message
//----------------------------------------------------------------------------
static void Decode_MidiMsg(DWORD msg)
{
	uint8_t midi_status = msg&0xff;
	uint8_t midi_chan	= midi_status & 0x0f;
	uint8_t midi_b1 = (msg>>0x08)&0xff;
	uint8_t midi_b2 = (msg>>0x10)&0xff;
	uint16_t pb=0;

	midi_b1 &= 0x7f;
	midi_b2 &= 0x7f;
	midi_status &= 0xf0;

	switch (midi_status) {
	case NOTE_OFF:
		printf("Note off (0x80)       chan:%02d key: %03d vel:%d\n", midi_chan, midi_b1, midi_b2);
		break;

	case NOTE_ON:
		if (midi_b2 != 0)
			printf("Note on	 (0x90)       chan:%02d key: %03d vel:%d\n", midi_chan, midi_b1, midi_b2);
		else
			printf("Note off (0x90)       chan:%02d key: %03d vel:%d\n", midi_chan, midi_b1, midi_b2);
		break;

	case POLY_PRESSURE:
		printf("Poly Pressure         chan:%02d key: %03d pressure:%d\n", midi_chan, midi_b1, midi_b2);
		break;

	case CONTINUOUS_CONTROLLER:
		printf("Continuous Controller chan:%02d controller: %d (%s) value:%d\n", midi_chan, midi_b1, getCCString(midi_b1), midi_b2);
		break;

	case PROGRAM_CHANGE:
		printf("Program Change        chan:%02d program: %d\n", midi_chan, midi_b1);
		break;

	case CHANNEL_PRESSURE:
		printf("Channel Pressure      chan:%02d value: %d\n", midi_chan, midi_b1);
		break;

	case PITCH_BEND:
		pb = midi_b2<<7|midi_b1;
		printf("Pitch Bend            chan:%02d value: %d\n", midi_chan, pb);
		break;

	default:
		printf("Unknown status: %02x\n", midi_status);
		break;
	}
}

//------------------------------------------------------------------------------
//	brief
//		Display about
//
//	param
//		none
//
//	return
//		none
//------------------------------------------------------------------------------
static void about(void)
{
	bldinfoPrintBldInfo();
	poptPrintUsage(optCon, stderr, 0);
	exit(1);
}

//
//	End: midi_decoder.c
//
